package cn.wsxiot.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 数据库工具类
 */
public class DBUtil {
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url="jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=UTF-8";
    private static final String username="root";
    private static final String password="root";

    private static Connection conn=null;

    //静态代码块负责加载驱动
    static {
        try {
            Class.forName(driver);
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    //单例模式返回数据库连接对象
    public static Connection getConnection() throws Exception {
        if(conn==null) {
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        }
        return conn;
    }
}
